package com.hlkj.baojin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.hlkj.baojin.constant.BaojinConstant;
import com.hlkj.baojin.constant.enums.SmsTypeEnum;
import com.hlkj.baojin.dao.IDutyDao;
import com.hlkj.baojin.entity.AlarmRecord;
import com.hlkj.baojin.entity.Duty;
import com.hlkj.baojin.entity.EarlyAlarmRecord;
import com.hlkj.baojin.entity.SocketMsg;
import com.hlkj.baojin.entity.dto.CompanyDto;
import com.hlkj.baojin.entity.dto.DeviceDto;
import com.hlkj.baojin.entity.enums.DeviceTypeEnum;
import com.hlkj.baojin.jwt.JwtUser;
import com.hlkj.baojin.service.*;
import com.hlkj.baojin.soket.MyWebSocket;
import com.hlkj.baojin.utils.LogUtils;
import com.hlkj.baojin.utils.MoblieMessageUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SmsServiceImpl implements SmsService {

    private final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);

    @Value("${jwt.backstage.phone}")
    private String backStagePhone;
    @Value("${spring.sms.plat}")
    private String SMS_PLATFORM;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ICompanyAreaService companyAreaService;
    @Autowired
    private MoblieMessageUtil moblieMessageUtil;
    @Autowired
    private IDutyDao dutyDao;


    /**
     * 根据类型发送手机短信
     *
     * @param phoneNumber 发送手机号
     * @param smsTypeEnum 枚举
     * @param param       枚举对应的参数
     */
    @Override
    @Async
    public void sendSms(String phoneNumber, SmsTypeEnum smsTypeEnum, String... param) {
        if ("alicloud".equals(SMS_PLATFORM)) {
            SendSmsResponse sendSmsResponse = MoblieMessageUtil.sendSmsAli(phoneNumber, smsTypeEnum, param);
            if ("OK".equals(sendSmsResponse.getCode())) {
                logger.info(LogUtils.module("手机短信").msg("发送成功")
                        .args("phone", phoneNumber)
                        .args("类型", smsTypeEnum)
                        .args("参数", StringUtils.join(param, ","))
                        .build());
            } else {
                logger.error(LogUtils.module("手机短信").msg("发送失败")
                        .args("phone", phoneNumber)
                        .args("类型：", smsTypeEnum)
                        .args("参数", StringUtils.join(param, ","))
                        .build());
            }
        }else if("mascloud".equals(SMS_PLATFORM)) {
            if(moblieMessageUtil.sendSmsMas(phoneNumber, smsTypeEnum, param)){
                logger.info(LogUtils.module("手机短信").msg("发送成功")
                        .args("phone", phoneNumber)
                        .args("类型", smsTypeEnum)
                        .args("参数", StringUtils.join(param, ","))
                        .build());
            }else{
                logger.error(LogUtils.module("手机短信").msg("发送失败")
                        .args("phone", phoneNumber)
                        .args("类型：", smsTypeEnum)
                        .args("参数", StringUtils.join(param, ","))
                        .build());
            }
        }else{
            logger.error("配置文件平台类型配置错误");
        }
    }

    @Override
    @Async
    public void sendAlarmSms(AlarmRecord alarmRecord, boolean sendSocket) {
        CompanyDto company = companyService.findCompanyById(alarmRecord.getCompanyId());
        DeviceDto device = deviceService.findDeviceById(alarmRecord.getDeviceId());

        if (sendSocket) {
            MyWebSocket.sendInfo(new SocketMsg(1, alarmRecord.getId()), userService.getByUsername(company.getCompanyPrincipalPhone()).getId(), userService.getByTypeIsAdmin().getId());
        }
        List<Duty> duty = dutyDao.findByDutyStatusAndDelete(1, BaojinConstant.IS_NO_DELETE);
//        后台
        duty.forEach(d -> {
            sendSms(d.getMobilePhone(), SmsTypeEnum.ALARM_TO_ADMIN, company.getName() + BaojinConstant.MONITOR_TYPE.get(device.getMonitorType()),
                    companyAreaService.getCompanyAreaNameByCompanyAreaId(device.getCompanyArea()) + device.getMonitorObject(), alarmRecord.getAlarmContent());
        });

        Set<String> phoneSet = new HashSet<>();
        phoneSet.add(company.getLegalPersonPhone());
        phoneSet.add(company.getCompanyPrincipalPhone());
        phoneSet.add(company.getCenterControlPrincipalPhone());
        phoneSet.forEach(phone -> {
            sendSms(phone, SmsTypeEnum.ALARM_TO_COMPANY,
                    BaojinConstant.MONITOR_TYPE.get(device.getMonitorType()),
                    companyAreaService.getCompanyAreaNameByCompanyAreaId(device.getCompanyArea()) + device.getMonitorObject(),
                    device.getMonitorArticle() + alarmRecord.getAlarmContent(),
                    DeviceTypeEnum.match(device.getMonitorType()) + "情况");
        });
    }

    @Override
    @Async
    public void sendEarlyAlarmSms(EarlyAlarmRecord alarmRecord, boolean sendSocket) {
        CompanyDto company = companyService.findCompanyById(alarmRecord.getCompanyId());
        DeviceDto device = deviceService.findDeviceById(alarmRecord.getDeviceId());

        if (sendSocket) {
            MyWebSocket.sendInfo(new SocketMsg(2, alarmRecord.getId()), userService.getByUsername(company.getCompanyPrincipalPhone()).getId(), userService.getByTypeIsAdmin().getId());
        }

        List<Duty> duty = dutyDao.findByDutyStatusAndDelete(1, BaojinConstant.IS_NO_DELETE);
//        后台
        duty.forEach(d -> {
            sendSms(d.getMobilePhone(), SmsTypeEnum.EARLY_ALARM_TO_ADMIN, company.getName() + BaojinConstant.MONITOR_TYPE.get(device.getMonitorType()),
                    companyAreaService.getCompanyAreaNameByCompanyAreaId(device.getCompanyArea()) + device.getMonitorObject(), alarmRecord.getAlarmContent());
        });
        //预警发送至中控负责人
        sendSms(company.getCenterControlPrincipalPhone(),
                SmsTypeEnum.EARLY_ALARM_TO_COMPANY,
                BaojinConstant.MONITOR_TYPE.get(device.getMonitorType()),
                companyAreaService.getCompanyAreaNameByCompanyAreaId(device.getCompanyArea()) + device.getMonitorObject(),
                device.getMonitorArticle() + alarmRecord.getAlarmContent(),
                DeviceTypeEnum.match(device.getMonitorType()) + "情况");
    }
}
